package org.liveboardgames.agricola.control.delegates
{
    import com.adobe.cairngorm.business.ServiceLocator;
    import com.adobe.cairngorm.control.CairngormEventDispatcher;
    
    import flash.utils.setTimeout;
    
    import mx.rpc.IResponder;
    
    import org.liveboardgames.agricola.control.delegates.helper.GameHelper;
    import org.liveboardgames.agricola.control.events.StartHarvestEvent;
    import org.liveboardgames.agricola.control.events.StartRoundEvent;
    import org.liveboardgames.agricola.vo.Game;
    import org.liveboardgames.agricola.vo.player.Player;
    
    public class EndTurnDelegate
    {
        private var _responder:IResponder;
        
        private var _service:Object;
        
        public function EndTurnDelegate(responder:IResponder)
        {
            this._service = ServiceLocator.getInstance().getRemoteObject( "roundService" );
            this._responder = responder;
        }
        
        public function endTurn(game:Game):void
        {
        	 var call:Object = _service.endTurn(game.id);
			call.resultHandler = _responder.result;
			call.faultHandler = _responder.fault;
            //setTimeout(completeTurn, 0, game);
        }
        
        private function completeTurn(game:Game):void
        {
            trace("Ending turn");
            // Get the next player to play
            var nextPlayer:Player = GameHelper.findNextPlayerToPlay(game);
            
            // If no one can play, the round is finished
            if (nextPlayer == null)
            {
                finishRound(game);
            }
            // Else, initialize the next player
            else
            {
                //AgricolaModelLocator.getInstance().workflowState = AgricolaModelLocator.ACTION_PENDING_STATE;
                game.hasPlayerPlayedPeep = false;
                game.currentPlayer = nextPlayer;
            }
        
            //_responder.result(newData);
        }
        
        private function finishRound(game:Game):void
        {
            // Send all peeps home
//            GameHelper.sendAllPeepsHome(game);
            
            // Harvest is needed
            var isHarvest:Boolean = GameHelper.isHarvest(game);
            if (isHarvest)
            {
            	var startHarvestEvent:StartHarvestEvent = new StartHarvestEvent(StartHarvestEvent.START_HARVEST);
            	startHarvestEvent.game = game;
                CairngormEventDispatcher.getInstance().dispatchEvent(startHarvestEvent);
            }
            else
            {
                // Else go on
                var startRoundEvent:StartRoundEvent = new StartRoundEvent(StartRoundEvent.START_ROUND);
                startRoundEvent.game = game;
                CairngormEventDispatcher.getInstance().dispatchEvent(startRoundEvent);
            }
        }
    }
}